package com.my.trie;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WangLuoXin
 * &#064;Date 2024/9/13  13:35
 **/
public class FilterTreeNode {
    //节点名称
    private final String name;

    //下级节点
    private List<FilterTreeNode> children;

    //是否为尾节点
    private Boolean isEnd = Boolean.FALSE;



    public FilterTreeNode(String name, List<FilterTreeNode> children) {
        this.name = name;
        this.children = children;
    }


    public void putPath(String path) {
        FilterTreeNode parent = this;
        String[] paths = path.split("/");
        for (int i = 0; i < paths.length; i++) {
            String name = paths[i];
            if (i == 0) {
                continue;
            }

            boolean isMatch = false;
            List<FilterTreeNode> newChildrenList = parent.children;
            for (FilterTreeNode treeNode : newChildrenList) {
                if (treeNode.name.equals(name)) {
                    isMatch = true;
                    parent = treeNode;
                    if (i == paths.length - 1) {
                        parent.isEnd = Boolean.TRUE;
                    }
                    break;
                }
            }
            if (!isMatch) {
                FilterTreeNode node;
                node = new FilterTreeNode(name, new ArrayList<>());
                if (i == paths.length - 1) {
                    node.isEnd = Boolean.TRUE;
                }
                newChildrenList.add(node);
                parent.children = newChildrenList;
                parent = node;
            }
        }
    }

    public Boolean getPath(String path) {
        FilterTreeNode parent = this;
        String[] paths = path.split("/");
        for (int i = 0; i < paths.length; i++) {
            if (i == 0) {
                continue;
            }
            List<FilterTreeNode> newChildrenList = parent.children;
            for (FilterTreeNode treeNode : newChildrenList) {
                if (treeNode.name.equals("**")) {
                    return Boolean.TRUE;
                }
                if (treeNode.name.equals(paths[i]) || (treeNode.name.startsWith("*") && treeNode.name.endsWith("*"))) {
                    parent = treeNode;
                    if (i == paths.length - 1) {
                        if (parent.isEnd) {
                            return Boolean.TRUE;
                        }
                        return Boolean.FALSE;
                    }
                    break;
                }
            }
        }
        return Boolean.FALSE;
    }


    @Override
    public String toString() {
        return "FilterTreeNode{" +
                "name='" + name + '\'' +
                ", children=" + children +
                ", isEnd=" + isEnd +
                '}';
    }

    public Boolean getEnd() {
        return isEnd;
    }
}
